﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Diagnostics;

namespace ShadowEraDeckEditor
{
    public partial class FormUpdate : Form
    {

        string programPath = Path.GetDirectoryName(Application.ExecutablePath);
        Settings Settings = new Settings();
        string updateAppVer;
        string updateDatVer;
        bool AppDownloaded = false;
        bool Continue = false;
        static string appUpdaterURL = "http://dl.dropbox.com/u/30391649/se%20deck%20editor/update.exe";
        static string appVersionURL = "http://dl.dropbox.com/u/30391649/se%20deck%20editor/versions.ini";
        //static string datVersionURL = "";

        public FormUpdate()
        {
            InitializeComponent();
        }

        private void FormUpdateDat_Load(object sender, EventArgs e)
        {
            
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if(button1.Text != "Close Window"){ 
            button1.Enabled = false; 
            label2.Text = "Connecting to server..";
            Application.DoEvents();
            MemoryStream inputStream = new MemoryStream();
            WebClient client = new WebClient();
            try
            {

                inputStream = new MemoryStream(client.DownloadData(appVersionURL));
                inputStream.Position = 0;
                using (StreamReader reader = new StreamReader(inputStream))
                {
                    updateAppVer = reader.ReadLine();
                    updateDatVer = reader.ReadLine();
                }
                client.Dispose();
                label2.Text = "Checking Version";
                Application.DoEvents();
                if (Settings.datVersion != updateDatVer)
                {
                    UpdateDat();
                }
                if ((Settings.appVersion != updateAppVer) && (Settings.datVersion == updateDatVer))
                {
                    UpdateApp();
                }
                if ((Settings.appVersion == updateAppVer) && (Settings.datVersion == updateDatVer))
                {
                    MessageBox.Show("No updates available");
                    this.Close();
                }
            }
            catch (Exception upEx)
            {

                MessageBox.Show(upEx.ToString());
           }
                }
        }

        void client_ProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            double bytesIn = double.Parse(e.BytesReceived.ToString());
            double bytesTotal = double.Parse(e.TotalBytesToReceive.ToString());
            double percent = bytesIn / bytesTotal * 100;

            progressBar1.Value = int.Parse(Math.Truncate(percent).ToString());
        }
        void client_ProgressChanged2(object sender, DownloadProgressChangedEventArgs e)
        {
            double bytesIn = double.Parse(e.BytesReceived.ToString());
            double bytesTotal = double.Parse(e.TotalBytesToReceive.ToString());
            double percent = bytesIn / bytesTotal * 100;

            progressBar1.Value = int.Parse(Math.Truncate(percent).ToString());
        }
        void client_downloadfinished(object sender, AsyncCompletedEventArgs e)
        {
            progressBar1.Value = 0;
            string programPathTMP = programPath + "\\carddb.dat.tmp";
            string programPathTMP2 = programPath + "\\carddb.dat";
            if(File.Exists(programPathTMP))
                File.Delete(programPathTMP2);
            File.Move(programPathTMP, programPathTMP2);
            if (Settings.appVersion == updateAppVer)
            {
                label2.Text = "Updates complete!";
                Continue = true;
                button1.Enabled = true;
                button1.Text = "Close Window";
            }
            else
                UpdateApp();
        }
        void client_programUpdate(object sender, AsyncCompletedEventArgs e)
        {
            string programPathAPP = programPath + "\\app.exe.tmp";
            if (File.Exists(programPathAPP))
            {
                Process updater = new Process();
                updater.StartInfo.FileName = "update.exe";
                updater.Start();
                Application.Exit();
            }
        }
        void client_appUpdate(object sender, AsyncCompletedEventArgs e)
        {
            try
            {
                label2.Text = "Downloading Updater";
                Application.DoEvents();
                string appUpdaterPath = programPath + "\\update.exe";

                WebClient updaterClient = new WebClient();
                updaterClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_ProgressChanged);
                updaterClient.DownloadFileCompleted += new AsyncCompletedEventHandler(client_programUpdate);
                updaterClient.DownloadFileAsync(new Uri(appUpdaterURL), appUpdaterPath);
                updaterClient.Dispose();
            }
            catch (Exception upEx)
            {
                MessageBox.Show(upEx.ToString());
            }
        }

        void UpdateDat()
        {
            try
            {
                label2.Text = "Updating Database";
                string programPathTMP = programPath + "\\carddb.dat.tmp";
                string datupateURL = "http://dl.dropbox.com/u/30391649/se%20deck%20editor/carddb." + updateDatVer + ".dat";
                WebClient datclient = new WebClient();

                datclient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_ProgressChanged2);
                datclient.DownloadFileCompleted += new AsyncCompletedEventHandler(client_downloadfinished);

                datclient.DownloadFileAsync(new Uri(datupateURL), programPathTMP);
                datclient.Dispose();
            }
            catch (Exception upEx)
                {
                MessageBox.Show(upEx.ToString());
                }
        }

        void UpdateApp()
        {
            try
            {
                label2.Text = "Updating Application";
                Application.DoEvents();
                AppDownloaded = true;
                string programPathAppTMP = programPath + "\\app.exe.tmp";
                string appupdateURL = "http://dl.dropbox.com/u/30391649/se%20deck%20editor/ShadowEraMultiTool." + updateAppVer + ".exe";

                WebClient appClient = new WebClient();
                appClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_ProgressChanged);
                appClient.DownloadFileCompleted += new AsyncCompletedEventHandler(client_appUpdate);
                appClient.DownloadFileAsync(new Uri(appupdateURL), programPathAppTMP);
                appClient.Dispose();
            }
                catch (Exception upEx)
                {
                MessageBox.Show(upEx.ToString());
                }
        }
    }
}
